package com.java.simple.study.juc.p3.reentrant;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhoujl
 * @date 2022/5/11 20:16
 * @desc
 */
@Slf4j(topic = "c.TestFair")
public class TestFair {

    // 布尔值控制是否公平锁
    static final ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        // 主线程上锁
        lock.lock();
        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }
        // 1s后另一个线程加入争抢
        Sleeper.sleep(1);
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " start...");
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "running...");
            } finally {
                lock.unlock();
            }
        }, "强行插入").start();
        /**
         * 非公平锁的情况下 强行插入线程有机会在中间抢到锁
         * 公平锁的情况下  强行插入线程一定是在最后抢到锁
         */
        lock.unlock();
    }

}
